<template>
  <div>
    <el-dialog
      :model-value="visible"
      title="新增用户"
      width="500"
      :close-on-click-modal="false"
      @close="cls"
    >
      <el-form :model="user">
        <el-form-item label="用户名">
          <el-input v-model="user.username" />
        </el-form-item>
        <el-form-item label="用户密码">
          <el-input v-model="user.password" type="password" show-password />
        </el-form-item>
        <el-form-item label="用户性别">
          <el-radio-group v-model="user.sex">
            <el-radio :value="1" size="large">保密</el-radio>
            <el-radio :value="2" size="large">男</el-radio>
            <el-radio :value="3" size="large">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="用户角色">
          <el-select v-model="user.role.roleid" placeholder="请选择用户角色">
            <el-option
              v-for="item in roleList"
              :key="item.roleid"
              :label="item.rolename"
              :value="item.roleid"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cls">关闭</el-button>
          <el-button type="primary" @click="save"> 保存 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { onBeforeMount, ref } from "vue";
import { ElMessage } from "element-plus";
import http from "@/utils/http2.js";
const user = ref({
  username: "",
  password: "",
  role: { roleid: null, rolename: "" }
});

//定义组件属性
const props = defineProps({
  visible: {
    type: Boolean,
    default: true
  }
});

//定义事件
const emits = defineEmits(["close"]);
function cls() {
  emits("close");
}

//定义角色列表数组
const roleList = ref([]);
async function getRoles() {
  let res = await http.get("/role");
  roleList.value = res;
}

//保存
async function save() {
  //发送数据
  let res = await http.post("/user", user.value);
  ElMessage({
    message: "保存成功",
    type: "success"
  });
  cls();
}
//钩子函数
onBeforeMount(() => {
  getRoles();
});
</script>
<style scoped></style>
